package net.lahuobao.finance.controller.reccode;
import java.util.Date;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.lahuobao.finance.dao.RecCode_UserDaoMapper;
import net.lahuobao.finance.entity.reccode.RecCode_User;
import org.apache.log4j.Logger;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import net.lahuobao.finance.entity.reccode.ReccodeEntity;
import net.lahuobao.finance.service.reccode.ReccodeServiceI;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;

/**   
 * @Title: Controller
 * @Description: 推荐码管理
 * @author zhangdaihao
 * @date 2016-08-24 18:11:05
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/reccodeController")
public class ReccodeController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ReccodeController.class);

	@Autowired
	private ReccodeServiceI reccodeService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;

	@Autowired
	private RecCode_UserDaoMapper recCodeUserDao;



	/**
	 * 推荐码管理列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("net/lahuobao/finance/reccode/reccodeList");
	}

//	/**
//	 * easyui AJAX请求数据
//	 *
//	 * @param request
//	 * @param response
//	 * @param dataGrid
//	 * @param user
//	 */
//	@RequestMapping(params = "datagrid")
//	public void datagrid(ReccodeEntity reccode,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
//		CriteriaQuery cq = new CriteriaQuery(ReccodeEntity.class, dataGrid);
//		//查询条件组装器
//		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, reccode, request.getParameterMap());
//		this.reccodeService.getDataGridReturn(cq, true);
//		//循环查询出当前机构的名称
//		List<ReccodeEntity> lists = cq.getDataGrid().getResults();
//		List<ReccodeEntity> cLists = new ArrayList<ReccodeEntity>();
//		for (ReccodeEntity reccodeEntity : lists){
//			if(reccodeEntity.getHoldertype() == 0){		//组织机构
//				TSDepart depart = reccodeService.getEntity(TSDepart.class,reccodeEntity.getHolder());
//				ReccodeEntity reccodeEntity2 = new ReccodeEntity();
//				reccodeEntity2.setHolder(depart.getDepartname());
//				reccodeEntity2.setHoldertype(0);
//				reccodeEntity2.setRemarks(reccodeEntity.getRemarks());
//				reccodeEntity2.setCreatetime(reccodeEntity.getCreatetime());
//				reccodeEntity2.setRecCode(reccodeEntity.getRecCode());
//				reccodeEntity2.setId(reccodeEntity.getId());
//				cLists.add(reccodeEntity2);
//			}else if(reccodeEntity.getHoldertype() == 1){	//会员
//				RecCode_User recCodeUser = recCodeUserDao.memberName(Long.parseLong(reccodeEntity.getHolder()));
//				ReccodeEntity reccodeEntity2 = new ReccodeEntity();
//				reccodeEntity2.setHolder(recCodeUser.getMemberName());
//				reccodeEntity2.setHoldertype(1);
//				reccodeEntity2.setRemarks(reccodeEntity.getRemarks());
//				reccodeEntity2.setCreatetime(reccodeEntity.getCreatetime());
//				reccodeEntity2.setRecCode(reccodeEntity.getRecCode());
//				reccodeEntity2.setId(reccodeEntity.getId());
//				cLists.add(reccodeEntity2);
//			}else{
//				cLists.add(reccodeEntity);
//			}
//		}
//		cq.getDataGrid().setResults(cLists);
//		TagUtil.datagrid(response, dataGrid);
//	}

	/**
	 * easyui AJAX请求数据
	 *
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "datagrid")
	public void datagrid(ReccodeEntity reccode,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ReccodeEntity.class, dataGrid);
		Map<String,Object> serachParams = new HashMap<String, Object>();
		String queryParams_memberName 	= request.getParameter("holder");
		String queryParams_recCode 		= request.getParameter("recCode");						//按照谁排序
		String queryParams_order		= request.getParameter("order");
		String queryParams_sort			= request.getParameter("sort");						//排序方式
		String queryParams_page			= request.getParameter("page");						//当前页
		String queryParams_rows			= request.getParameter("rows");						//页数大小
		if(queryParams_memberName 	!= null && queryParams_memberName.trim().length() 	> 0){serachParams.put("memberName",queryParams_memberName);}else{serachParams.put("memberName",null);}
		if(queryParams_recCode 		!= null && queryParams_recCode.trim().length() 		> 0){serachParams.put("recCode",queryParams_recCode);}else{serachParams.put("recCode",null);}
		if(queryParams_sort 		!= null && queryParams_sort.trim().length() 		> 0){
			if("holder".equals(queryParams_sort)){	queryParams_sort = "memberName";}
			if("recCode".equals(queryParams_sort)){	queryParams_sort = "rec_code";}
			if("showCreateTime".equals(queryParams_sort)){queryParams_sort = "createTime";}
			if("memberName".equals(queryParams_sort) || "rec_code".equals(queryParams_sort) || "createTime".equals(queryParams_sort)){
				serachParams.put("sort",queryParams_sort);
			}else{
				serachParams.put("sort",null);
			}
		}
		if(queryParams_order		!= null && queryParams_order.trim().length() 		> 0){
			if("asc".equals(queryParams_order) || "desc".equals(queryParams_order)){serachParams.put("order",queryParams_order);}else{serachParams.put("order","asc");}
		}
		try{
			serachParams.put("startIndex",(Integer.parseInt(queryParams_page)-1)*Integer.parseInt(queryParams_rows));
			serachParams.put("endIndex",Integer.parseInt(queryParams_rows));
		}catch (Exception e){
			serachParams.put("startIndex",1);
			serachParams.put("endIndex","10");
		}
		int count = recCodeUserDao.serachRecCodesCount(serachParams);	//当前查询总条数
		List<ReccodeEntity> recCodes = recCodeUserDao.serachRecCodes(serachParams);
		cq.getDataGrid().setTotal(count);
		cq.getDataGrid().setResults(recCodes);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除推荐码管理
	 * @return
	 *
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(ReccodeEntity reccode, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		reccode = systemService.getEntity(ReccodeEntity.class, reccode.getId());
		message = "推荐码管理删除成功";
		reccode.setStatus(0);//逻辑删除
		reccodeService.saveOrUpdate(reccode);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加推荐码管理
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(ReccodeEntity reccode, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(reccode.getId())) {
			message = "推荐码管理更新成功";
			ReccodeEntity t = reccodeService.get(ReccodeEntity.class, reccode.getId());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(reccode, t);
				reccodeService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
				message = "推荐码管理更新失败";
			}
		} else {
			message = "推荐码管理添加成功";
			reccodeService.save(reccode);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 推荐码管理列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(ReccodeEntity reccode, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(reccode.getId())) {
			//reccode = reccodeService.getEntity(ReccodeEntity.class, reccode.getId());
			RecCode_User recCodeUser = recCodeUserDao.serachUserInfoById(reccode.getId());
			req.setAttribute("reccodePage", recCodeUser);
		}
		return new ModelAndView("net/lahuobao/finance/reccode/reccode");
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<ReccodeEntity> list() {
		List<ReccodeEntity> listReccodes=reccodeService.getList(ReccodeEntity.class);
		return listReccodes;
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> get(@PathVariable("id") String id) {
		ReccodeEntity task = reccodeService.get(ReccodeEntity.class, id);
		if (task == null) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(task, HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<?> create(@RequestBody ReccodeEntity reccode, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<ReccodeEntity>> failures = validator.validate(reccode);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		reccodeService.save(reccode);

		//按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
		String id = reccode.getId();
		URI uri = uriBuilder.path("/rest/reccodeController/" + id).build().toUri();
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(uri);

		return new ResponseEntity(headers, HttpStatus.CREATED);
	}


	/***
	 * 根据用户名查询用户信息
	 *
	 * @param memberName 会员名称
	 *
	 * @return map
	 */
	@RequestMapping(params = "serachUserInfo",method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson serachUserInfo(String memberName,HttpServletResponse response){
		AjaxJson ajaxJson = new AjaxJson();
		Map<String,Object> map = new HashMap<String, Object>();
		if(memberName == null){
			map.put("status","-1");
			map.put("message","数据错误");
			ajaxJson.setAttributes(map);
			return ajaxJson;
		}
		RecCode_User recCodeUser = recCodeUserDao.serachUserInfo(memberName);
		if(recCodeUser == null){
			map.put("status","-2");
			map.put("message","对不起，无此登陆名！");
			ajaxJson.setAttributes(map);
			return ajaxJson;
		}else{
			map.put("status","1");
			map.put("message","SUCCESS");
			map.put("info",recCodeUser);
			ajaxJson.setAttributes(map);
		}
		return ajaxJson;
	}


//	/***
//	 * 为用户绑定推荐码
//	 *
//	 * @param userId 用户编号
//	 * @return
//	 */
//	@RequestMapping(params = "createRecCode",method = RequestMethod.POST)
//	@ResponseBody
//	public AjaxJson createRecCodeByUser(long userId,String userName){
//		AjaxJson aj = new AjaxJson();
//		Map<String,Object> result = new HashMap<String, Object>();
//		//检查用户是否存在
//		Map<String,Object> params = new HashMap<String, Object>();
//		params.put("userId",userId);
//		params.put("userName",userName);
//		int userCount = recCodeUserDao.serachUserCountByUserIdAndMemberName(params);
//		if(userCount < 1){
//			//当前用户不存在
//			result.put("status","-1");
//			result.put("message","用户不存在");
//			aj.setAttributes(result);
//			return aj;
//		}
//		//检查用户是否已经生成了推荐码
//		int recCount = recCodeUserDao.serachRecCodeCountByUserId(userId);
//		if(recCount > 0){
//			//当前用户已经生成了推荐码
//			result.put("status","-2");
//			result.put("message","用户已经生成推荐码");
//			aj.setAttributes(result);
//			return aj;
//		}
//		//推荐码部分
//		String rec_code = ""+(1+getMaxRecCode());
//		if(rec_code.length() == 1){rec_code = "00000"+rec_code;}
//		if(rec_code.length() == 2){rec_code = "0000"+rec_code;}
//		if(rec_code.length() == 3){rec_code = "000"+rec_code;}
//		if(rec_code.length() == 4){rec_code = "00"+rec_code;}
//		if(rec_code.length() == 5){rec_code = "0"+rec_code;}
//		ReccodeEntity reccodeEntity = new ReccodeEntity();
//		reccodeEntity.setCreatetime(new Date());
//		reccodeEntity.setHolder(userId+"");
//		reccodeEntity.setRecCode(rec_code);
//		reccodeEntity.setRemarks("为用户添加验证码");
//		reccodeEntity.setHoldertype(1);
//		reccodeService.save(reccodeEntity);
//		result.put("status","1");
//		result.put("recCode",rec_code);
//		aj.setAttributes(result);
//		return aj;
//	}




	/***
	 *
	 * 查询出当前级别的最大的邀请码
	 * @return	String 邀请码
	 */
	private synchronized int getMaxRecCode(){
		String sql = "select max(rec_code) as maxCode from t_s_rec_code";
		Map<String,Object> result = systemService.findOneForJdbc(sql);
		if(result == null || result.get("maxCode") == null){
			return 0;
		}else{
			return Integer.parseInt(result.get("maxCode").toString());
		}
	}


	@RequestMapping(params = "returnTrue")
	@ResponseBody
	public AjaxJson returnTrue(String userId,String userName) {
		AjaxJson aj = new AjaxJson();
		if(userId == null || userId.equals("") || userName == null || userName.equals("")){aj.setMsg("用户不存在");return aj;}
		try{Long.parseLong(userId);}catch (Exception e){aj.setMsg("用户不存在");return aj;}

		//检查用户是否存在
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("userId",userId);
		params.put("userName",userName);
		int userCount = recCodeUserDao.serachUserCountByUserIdAndMemberName(params);
		if(userCount < 1){	//当前用户不存在
			aj.setMsg("用户不存在");
			return aj;
		}
		//检查用户是否已经生成了推荐码
		int recCount = recCodeUserDao.serachRecCodeCountByUserId(Long.parseLong(userId));
		if(recCount > 0){	//当前用户已经生成了推荐码
			ReccodeEntity reccodeEntity = recCodeUserDao.getBylahuobaoUserId(userId + "");
			if(reccodeEntity != null && reccodeEntity.getStatus() == 0){//已经被删除了
				reccodeEntity.setStatus(1);
				reccodeService.saveOrUpdate(reccodeEntity);
				aj.setMsg("外部用户推荐码更新成功");
			}else{
				aj.setMsg("外部用户推荐码更新失败");
			}
			return aj;
		}
		//推荐码部分
		String rec_code = ""+(1+getMaxRecCode());
		if(rec_code.length() == 1){rec_code = "00000"+rec_code;}
		if(rec_code.length() == 2){rec_code = "0000"+rec_code;}
		if(rec_code.length() == 3){rec_code = "000"+rec_code;}
		if(rec_code.length() == 4){rec_code = "00"+rec_code;}
		if(rec_code.length() == 5){rec_code = "0"+rec_code;}
		ReccodeEntity reccodeEntity = new ReccodeEntity();
		reccodeEntity.setCreatetime(new Date());
		reccodeEntity.setHolder(userId+"");
		reccodeEntity.setRecCode(rec_code);
		reccodeEntity.setRemarks("为外部用户添加推荐码");
		reccodeEntity.setHoldertype(1);
		reccodeEntity.setStatus(1);
		reccodeService.save(reccodeEntity);
		aj.setMsg("添加推荐码成功");
		return aj;
	}


	/**
	 * 导出excel
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(ReccodeEntity reccodeEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap){
		Map<String,Object> serachParams = new HashMap<String, Object>();
		String queryParams_memberName 	= request.getParameter("holder");
		String queryParams_recCode 		= request.getParameter("recCode");
		String queryParams_sort			= request.getParameter("sort");						//按照谁排序
		String queryParams_order		= request.getParameter("order");					//排序方式
		if(queryParams_memberName 	!= null && queryParams_memberName.trim().length() 	> 0){serachParams.put("memberName",queryParams_memberName);}else{serachParams.put("memberName",null);}
		if(queryParams_recCode 		!= null && queryParams_recCode.trim().length() 		> 0){serachParams.put("recCode",queryParams_recCode);}else{serachParams.put("recCode",null);}
		if(queryParams_sort 		!= null && queryParams_sort.trim().length() 		> 0){
			if("holder".equals(queryParams_sort)){	queryParams_sort = "memberName";}
			if("recCode".equals(queryParams_sort)){	queryParams_sort = "rec_code";}
			if("memberName".equals(queryParams_sort) || "rec_code".equals(queryParams_sort) || "createtime".equals(queryParams_sort)){
				serachParams.put("sort",queryParams_sort);
			}else{
				serachParams.put("sort",null);
			}
		}
		if(queryParams_order		!= null && queryParams_order.trim().length() 		> 0){
			if("asc".equals(queryParams_order) || "desc".equals(queryParams_order)){serachParams.put("order",queryParams_order);}else{serachParams.put("order","asc");}
		}

		List<ReccodeEntity> recCodes = recCodeUserDao.serachRecCodes(serachParams);

		modelMap.put(NormalExcelConstants.FILE_NAME,"外部客户推荐码列表");
		modelMap.put(NormalExcelConstants.CLASS,ReccodeEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("外部客户推荐码列表", "导出人:"+ ResourceUtil.getSessionUserName().getRealName(),"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,recCodes);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

}
